package jgato.aplicacion;

import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import jgato.modelo.Ficha;
import jgato.modelo.Jugador;
import jgato.modelo.Red;
import jgato.modelo.Value;
import jgato.server.Server;
import jgato.server.modelo.Jugada;
import jgato.server.modelo.PeticionFicha;
import jgato.server.modelo.RespuestaFicha;
import jgato.server.modelo.Mensaje;

/**
 *
 * @author pperezp
 */
public class JGato extends javax.swing.JFrame {

    private Jugador j1;
    private Jugador j2;
    private Jugador turno;
    
    /*Para version server*/
    private Jugador yo;
    
    private Ficha[] tablero;
    private ServerSocket server;
    private Socket cliente;
    /*Contadores de veces ganadas*/
    private int contJ1;
    private int contJ2;
    private boolean conectado;

    /**
     * Creates new form JCat
     */
    public JGato() throws UnknownHostException {
        
        initComponents();
        
        establecerIp();
        
        this.setLocationRelativeTo(null);
        this.setTitle("JCat");
        contJ1 = 0;
        contJ2 = 0;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jFrame1 = new javax.swing.JFrame();
        jLabel1 = new javax.swing.JLabel();
        txtNombreServidor2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtServidor = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jFrame2 = new javax.swing.JFrame();
        jLabel4 = new javax.swing.JLabel();
        txtNombreServer = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        cboFichaServer = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        pos4 = new javax.swing.JLabel();
        pos3 = new javax.swing.JLabel();
        pos1 = new javax.swing.JLabel();
        pos6 = new javax.swing.JLabel();
        pos2 = new javax.swing.JLabel();
        pos7 = new javax.swing.JLabel();
        pos8 = new javax.swing.JLabel();
        pos5 = new javax.swing.JLabel();
        pos9 = new javax.swing.JLabel();
        btnJugar = new javax.swing.JButton();
        lblTurno = new javax.swing.JLabel();
        lblTurno1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        lblJu1 = new javax.swing.JLabel();
        lblc1 = new javax.swing.JLabel();
        lblc2 = new javax.swing.JLabel();
        lblJu2 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        lblIpPublica = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        txtJugador1 = new javax.swing.JTextField();
        parte1 = new javax.swing.JRadioButton();
        cboFicha = new javax.swing.JComboBox();
        parte2 = new javax.swing.JRadioButton();
        lblFicha = new javax.swing.JLabel();
        txtJugador2 = new javax.swing.JTextField();
        lblIpLocal = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();

        jLabel1.setText("Nombre: ");

        jLabel2.setText("Servidor:");

        jButton2.setText("Conectar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                    .addComponent(txtNombreServidor2)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNombreServidor2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addContainerGap())
        );

        jLabel4.setText("Nombre: ");

        jButton4.setText("Compartir en red");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        cboFichaServer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "O", "X" }));
        cboFichaServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboFichaServerActionPerformed(evt);
            }
        });

        jLabel6.setText("Ficha:");

        javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane());
        jFrame2.getContentPane().setLayout(jFrame2Layout);
        jFrame2Layout.setHorizontalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtNombreServer)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)
                    .addComponent(cboFichaServer, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jFrame2Layout.setVerticalGroup(
            jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jFrame2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtNombreServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboFichaServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton4)
                .addContainerGap())
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        pos4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos4.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos4MouseReleased(evt);
            }
        });

        pos3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos3MouseReleased(evt);
            }
        });

        pos1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos1.setToolTipText("");
        pos1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos1MouseReleased(evt);
            }
        });

        pos6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos6.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos6MouseReleased(evt);
            }
        });

        pos2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos2MouseReleased(evt);
            }
        });

        pos7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos7.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos7.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos7MouseReleased(evt);
            }
        });

        pos8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos8.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos8.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos8MouseReleased(evt);
            }
        });

        pos5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos5.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos5MouseReleased(evt);
            }
        });

        pos9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pos9.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pos9.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                pos9MouseReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(pos7, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pos8, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(pos9, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(pos4, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pos5, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pos6, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(pos1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pos2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pos3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pos3, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pos2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pos1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pos4, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pos5, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pos6, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pos7, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pos8, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(pos9, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnJugar.setText("Jugar!");
        btnJugar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnJugarActionPerformed(evt);
            }
        });

        lblTurno.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        lblTurno.setText("Juega:");

        lblTurno1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        lblTurno1.setForeground(new java.awt.Color(255, 0, 0));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resultados"));

        lblJu1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblc1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblc1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblc1.setText("0");
        lblc1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblc2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblc2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblc2.setText("0");
        lblc2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblJu2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblJu1, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
                    .addComponent(lblJu2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblc2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblc1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblc1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblJu1, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblc2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblJu2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTextArea3.setColumns(20);
        jTextArea3.setLineWrap(true);
        jTextArea3.setRows(5);
        jTextArea3.setWrapStyleWord(true);
        jTextArea3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextArea3KeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jTextArea3);

        jTextArea2.setEditable(false);
        jTextArea2.setColumns(20);
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(5);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane2.setViewportView(jTextArea2);

        lblIpPublica.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblIpPublica.setForeground(new java.awt.Color(255, 0, 0));
        lblIpPublica.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblIpPublica.setText("Sin conexión");
        lblIpPublica.setBorder(javax.swing.BorderFactory.createTitledBorder("IP Pública"));

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        buttonGroup1.add(parte1);
        parte1.setSelected(true);
        parte1.setText("Parte jugando");

        cboFicha.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "O", "X" }));
        cboFicha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboFichaActionPerformed(evt);
            }
        });

        buttonGroup1.add(parte2);
        parte2.setText("Parte jugando");

        lblFicha.setText("X");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(txtJugador2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtJugador1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(parte1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(parte2, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblFicha, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cboFicha, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtJugador1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cboFicha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(parte1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtJugador2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblFicha, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(parte2))
                .addContainerGap())
        );

        lblIpLocal.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblIpLocal.setForeground(new java.awt.Color(255, 0, 0));
        lblIpLocal.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblIpLocal.setText("Sin conexión");
        lblIpLocal.setBorder(javax.swing.BorderFactory.createTitledBorder("IP Local"));

        jMenu1.setText("Multijugador");

        jMenuItem1.setText("Iniciar servidor");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Conectar");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnJugar, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addComponent(lblTurno, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(lblTurno1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblIpPublica, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                            .addComponent(lblIpLocal, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblIpPublica)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblIpLocal)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnJugar)
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblTurno, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTurno1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void pos4MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos4MouseReleased
        this.setFicha(4, pos4, turno.getFicha());
    }//GEN-LAST:event_pos4MouseReleased

    private void pos3MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos3MouseReleased
        this.setFicha(3, pos3, turno.getFicha());
    }//GEN-LAST:event_pos3MouseReleased

    private void pos1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos1MouseReleased
        this.setFicha(1, pos1, turno.getFicha());

    }//GEN-LAST:event_pos1MouseReleased

    private void pos6MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos6MouseReleased
        this.setFicha(6, pos6, turno.getFicha());
    }//GEN-LAST:event_pos6MouseReleased

    private void pos2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos2MouseReleased
        this.setFicha(2, pos2, turno.getFicha());
    }//GEN-LAST:event_pos2MouseReleased

    private void pos7MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos7MouseReleased
        this.setFicha(7, pos7, turno.getFicha());
    }//GEN-LAST:event_pos7MouseReleased

    private void pos8MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos8MouseReleased
        this.setFicha(8, pos8, turno.getFicha());
    }//GEN-LAST:event_pos8MouseReleased

    private void pos5MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos5MouseReleased
        this.setFicha(5, pos5, turno.getFicha());
    }//GEN-LAST:event_pos5MouseReleased

    private void pos9MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pos9MouseReleased
        this.setFicha(9, pos9, turno.getFicha());
    }//GEN-LAST:event_pos9MouseReleased

    private void btnJugarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnJugarActionPerformed
        this.reestablecerTablero();
        j1 = new Jugador(1, txtJugador1.getText(), (cboFicha.getSelectedIndex() == 0 ? Ficha.O : Ficha.X));
        j2 = new Jugador(2, txtJugador2.getText(), (cboFicha.getSelectedIndex() == 0 ? Ficha.X : Ficha.O));

        if (parte1.isSelected()) {
            turno = j1;
        } else {
            turno = j2;
        }

        lblTurno1.setText(turno.getNombre());
        btnJugar.setText("Jugar de nuevo");

        lblJu1.setText(j1.getNombre());
        lblJu2.setText(j2.getNombre());

        contJ1 = 0;
        contJ2 = 0;

        lblc1.setText("0");
        lblc2.setText("0");
    }//GEN-LAST:event_btnJugarActionPerformed

    private void cboFichaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboFichaActionPerformed
        if (cboFicha.getSelectedItem().toString().equalsIgnoreCase("O")) {
            lblFicha.setText("X");
        } else {
            lblFicha.setText("O");
        }
    }//GEN-LAST:event_cboFichaActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        this.jFrame2.setSize(203, 137);
        this.jFrame2.setLocationRelativeTo(this);
        this.jFrame2.setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        this.jFrame1.setSize(203, 137);
        this.jFrame1.setLocationRelativeTo(this);
        this.jFrame1.setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jTextArea3KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea3KeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            String mensaje = jTextArea3.getText();
            Mensaje men = new Mensaje(mensaje, yo.getNombre());

            enviarObjeto(men);


            jTextArea2.append("\n" + yo.getNombre() + ": " + mensaje);
            jTextArea3.setText("");
        }
    }//GEN-LAST:event_jTextArea3KeyReleased

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
       try {
            String sr = txtServidor.getText();
            
            cliente = new Socket(sr, 5000);
            
            enviarObjeto(new PeticionFicha());
            
            estado(false);
            
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ObjectInputStream input;
                    while (true) {
                        try {
                            input = new ObjectInputStream(cliente.getInputStream());
                            Object o = input.readObject();
                            if (o instanceof Mensaje) {
                                Mensaje m = (Mensaje) o;
                                jTextArea2.append("\n" + m.getEmisor() + ": " + m.getMensaje());
                            } else if (o instanceof Jugada) {
                                Jugada j = (Jugada) o;
                                setFicha(j.getPosicion(), j.getFicha());
                            } else if(o instanceof RespuestaFicha){
                                RespuestaFicha rf = (RespuestaFicha) o;
                                j2 = new Jugador(2, txtNombreServidor2.getText(), rf.getFicha());
                                
                                yo = j2;
                                
                                enviarObjeto(j2);
                                
                                
                            }else if(o instanceof Jugador){
                                Jugador primerJugador = (Jugador)o;
                                
                                j1 = primerJugador;
                                jFrame1.setVisible(false);
                                JOptionPane.showMessageDialog(null, "Su ficha es: "+j2.getFicha());
                                comenzarPartida();
                            }
                        } catch (IOException ex) {
                            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (ClassNotFoundException ex) {
                            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }
            }).start();
            conectado = true;
        } catch (UnknownHostException ex) {
            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        new Thread(new Server()).start();
        String nombre = txtNombreServer.getText();
        String ficha = cboFichaServer.getSelectedItem().toString();
        
        Jugador jugadorNuevo = new Jugador(1, nombre, (ficha.equalsIgnoreCase("x")?Ficha.X:Ficha.O));
        
        j1 = jugadorNuevo;
        yo = jugadorNuevo;
        estado(false);
        
        
        
        try {
            cliente = new Socket("localhost", 5000);
            enviarObjeto(j1);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ObjectInputStream input;
                    while (true) {
                        try {
                            input = new ObjectInputStream(cliente.getInputStream());
                            Object o = input.readObject();
                            
                            if (o instanceof Mensaje) {
                                Mensaje m = (Mensaje) o;
                                jTextArea2.append("\n" + m.getEmisor() + ": " + m.getMensaje());
                            } else if (o instanceof Jugada) {
                                Jugada j = (Jugada) o;
                                setFicha(j.getPosicion(), j.getFicha());
                            }else if(o instanceof Jugador){
                                Jugador jugador = (Jugador)o;
                                
                                j2 = jugador;
                                
                                comenzarPartida();
                            }
                        } catch (IOException | ClassNotFoundException ex) {
                            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    }
                }

                
            }).start();
            this.jFrame2.setVisible(false);
        } catch (UnknownHostException ex) {
            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
        }

        conectado = true;
    }//GEN-LAST:event_jButton4ActionPerformed

    private void cboFichaServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboFichaServerActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cboFichaServerActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JGato.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JGato.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JGato.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JGato.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new JGato().setVisible(true);
                } catch (UnknownHostException ex) {
                    Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnJugar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cboFicha;
    private javax.swing.JComboBox cboFichaServer;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JFrame jFrame2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextArea jTextArea3;
    private javax.swing.JLabel lblFicha;
    private javax.swing.JLabel lblIpLocal;
    private javax.swing.JLabel lblIpPublica;
    private javax.swing.JLabel lblJu1;
    private javax.swing.JLabel lblJu2;
    private javax.swing.JLabel lblTurno;
    private javax.swing.JLabel lblTurno1;
    private javax.swing.JLabel lblc1;
    private javax.swing.JLabel lblc2;
    private javax.swing.JRadioButton parte1;
    private javax.swing.JRadioButton parte2;
    private javax.swing.JLabel pos1;
    private javax.swing.JLabel pos2;
    private javax.swing.JLabel pos3;
    private javax.swing.JLabel pos4;
    private javax.swing.JLabel pos5;
    private javax.swing.JLabel pos6;
    private javax.swing.JLabel pos7;
    private javax.swing.JLabel pos8;
    private javax.swing.JLabel pos9;
    private javax.swing.JTextField txtJugador1;
    private javax.swing.JTextField txtJugador2;
    private javax.swing.JTextField txtNombreServer;
    private javax.swing.JTextField txtNombreServidor2;
    private javax.swing.JTextField txtServidor;
    // End of variables declaration//GEN-END:variables

    private void comenzarPartida() {
        JOptionPane.showMessageDialog(this, "Partida Comenzada");
        this.reestablecerTablero();
        turno = j1;

        lblTurno1.setText(turno.getNombre());
//        btnJugar.setText("Jugar de nuevo");

        lblJu1.setText(j1.getNombre());
        lblJu2.setText(j2.getNombre());

        contJ1 = 0;
        contJ2 = 0;

        lblc1.setText("0");
        lblc2.setText("0");
    }
    
    private void setFicha(int posicion, JLabel lbl, Ficha ficha) {
        if(conectado){
            if(turno.getId() == yo.getId()){
                if (posicionLibre(posicion)) {
                    lbl.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    tablero[posicion - 1] = ficha;

                    if (conectado) {
                        enviarObjeto(new Jugada(posicion, ficha));
                    }

                    if (hayAlgunGanador()) {
                        if (turno.getId() == 1) {
                            lblc1.setText(Integer.toString(++contJ1));
                        } else {
                            lblc2.setText(Integer.toString(++contJ2));
                        }

                        JOptionPane.showMessageDialog(this, "FELICIDADES " + turno.getNombre().toUpperCase());
                        this.reestablecerTablero();
                    } else if (ganoNadie()) {
                        JOptionPane.showMessageDialog(this, "GANÓ NADIE!");
                        this.reestablecerTablero();
                    }

                    turno = (turno.getId() == 1 ? j2 : j1);
                    lblTurno1.setText(turno.getNombre());
                }
            }
        }else {
            if (posicionLibre(posicion)) {
                lbl.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                tablero[posicion - 1] = ficha;

                
                if (hayAlgunGanador()) {
                    if (turno.getId() == 1) {
                        lblc1.setText(Integer.toString(++contJ1));
                    } else {
                        lblc2.setText(Integer.toString(++contJ2));
                    }

                    if (JOptionPane.showConfirmDialog(this, "FELICIDADES " + turno.getNombre().toUpperCase() + "!, Desea jugar de nuevo?", "Preungta", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                        this.reestablecerTablero();
                    }
                } else if (ganoNadie()) {
                    if (JOptionPane.showConfirmDialog(this, "GANÓ NADIE!, Desea jugar de nuevo?", "Pregunta", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                        this.reestablecerTablero();
                    }
                }

                turno = (turno.getId() == 1 ? j2 : j1);
                lblTurno1.setText(turno.getNombre());
            }
        }
        
        
    }

    private void setFicha(int posicion, Ficha ficha) {
        if (posicionLibre(posicion)) {
            switch (posicion) {
                case 1: {
                    pos1.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 2: {
                    pos2.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 3: {
                    pos3.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 4: {
                    pos4.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 5: {
                    pos5.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 6: {
                    pos6.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 7: {
                    pos7.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 8: {
                    pos8.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
                case 9: {
                    pos9.setIcon(new ImageIcon(getClass().getResource("/jgato/imagenes/" + ficha.name() + ".png")));
                    break;
                }
            }
            tablero[posicion - 1] = ficha;

            if (hayAlgunGanador()) {
                if (turno.getId() == 1) {
                    lblc1.setText(Integer.toString(++contJ1));
                } else {
                    lblc2.setText(Integer.toString(++contJ2));
                }

                JOptionPane.showMessageDialog(this, "FELICIDADES " + turno.getNombre().toUpperCase());
                this.reestablecerTablero();
            } else if (ganoNadie()) {
                JOptionPane.showMessageDialog(this, "GANÓ NADIE!");
                this.reestablecerTablero();
            }

            turno = (turno.getId() == 1 ? j2 : j1);
            lblTurno1.setText(turno.getNombre());

        }



    }

    private boolean hayAlgunGanador() {
        if ((tablero[0] == tablero[1] && tablero[1] == tablero[2])
                && (tablero[0] != null && tablero[1] != null && tablero[2] != null)) {
            ponerGato(pos1, pos2, pos3);
            return true;
        } else if ((tablero[3] == tablero[4] && tablero[4] == tablero[5])
                && (tablero[3] != null && tablero[4] != null && tablero[5] != null)) {
            ponerGato(pos4, pos5, pos6);
            return true;
        } else if ((tablero[6] == tablero[7] && tablero[7] == tablero[8])
                && (tablero[6] != null && tablero[7] != null && tablero[8] != null)) {
            ponerGato(pos7, pos8, pos9);
            return true;
        } else if ((tablero[0] == tablero[3] && tablero[3] == tablero[6])
                && (tablero[0] != null && tablero[3] != null && tablero[6] != null)) {
            ponerGato(pos1, pos4, pos7);
            return true;
        } else if ((tablero[1] == tablero[4] && tablero[4] == tablero[7])
                && (tablero[1] != null && tablero[4] != null && tablero[7] != null)) {
            ponerGato(pos2, pos5, pos8);
            return true;
        } else if ((tablero[2] == tablero[5] && tablero[5] == tablero[8])
                && (tablero[2] != null && tablero[5] != null && tablero[8] != null)) {
            ponerGato(pos3, pos6, pos9);
            return true;
        } else if ((tablero[0] == tablero[4] && tablero[4] == tablero[8])
                && (tablero[0] != null && tablero[4] != null && tablero[8] != null)) {
            ponerGato(pos1, pos5, pos9);
            return true;
        } else if ((tablero[2] == tablero[4] && tablero[4] == tablero[6])
                && (tablero[2] != null && tablero[4] != null && tablero[6] != null)) {
            ponerGato(pos3, pos5, pos7);
            return true;
        }
        return false;
    }

    private boolean ganoNadie() {
        int cont = 0;
        for (Ficha f : tablero) {
            if (f != null) {
                cont++;
            }
        }

        return cont == 9;
    }

    private void reestablecerTablero() {
//        for(int i=0; i<tablero.length; i++){
//            tablero[i] = null;
//        }
        tablero = new Ficha[9];
        pos1.setIcon(null);
        pos2.setIcon(null);
        pos3.setIcon(null);
        pos4.setIcon(null);
        pos5.setIcon(null);
        pos6.setIcon(null);
        pos7.setIcon(null);
        pos8.setIcon(null);
        pos9.setIcon(null);

    }

    private boolean posicionLibre(int posicion) {
        return tablero[posicion - 1] == null;
    }

    private void ponerGato(JLabel l1, JLabel l2, JLabel l3) {
        l1.setIcon(new ImageIcon(getClass().getResource(Value.IMAGEN_GATO)));
        l2.setIcon(new ImageIcon(getClass().getResource(Value.IMAGEN_GATO)));
        l3.setIcon(new ImageIcon(getClass().getResource(Value.IMAGEN_GATO)));
    }

    private void enviarObjeto(Object o) {
        ObjectOutputStream output;
        try {
            output = new ObjectOutputStream(cliente.getOutputStream());
            output.writeObject(o);
        } catch (IOException ex) {
            Logger.getLogger(JGato.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void estado(boolean estado) {
        txtJugador1.setEnabled(estado);
        txtJugador2.setEnabled(estado);
        btnJugar.setEnabled(estado);
        parte1.setEnabled(estado);
        parte2.setEnabled(estado);
        cboFicha.setEnabled(estado);
    }

    private void establecerIp() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    lblIpLocal.setText(Red.getIpLocal());
                    lblIpPublica.setText(Red.getIpPublica());
                } catch (IOException ex) {

                }
            }
        }).start();
    }
}
